﻿@using ZR.CodeGenerator
@using ZR.Model.System.Generate
@using Infrastructure.Extensions;
@using Microsoft.AspNetCore.Mvc.Rendering
@using Microsoft.AspNetCore.Mvc.ViewFeatures
@* @model ZR.CodeGenerator.Model.GenerateDto; *@
@{
    var genTable = Model.GenTable;
    var subTableOptions = Model.SubTableOptions;
    var options = Model.GenOptions;
    var replaceDto = Model.ReplaceDto;
    bool showCustomInput = Model.GenTable.Columns.Any((Func<GenTableColumn, bool>)(f => f.HtmlType.Equals(GenConstants.HTML_CUSTOM_INPUT, StringComparison.OrdinalIgnoreCase)));
    var index = 0;
    var dictHtml = new string[] { GenConstants.HTML_CHECKBOX, GenConstants.HTML_RADIO, GenConstants.HTML_SELECT, GenConstants.HTML_SELECT_MULTI };
    var dicts = new List<GenTableColumn>();
    dicts.AddRange(Model.GenTable.Columns.FindAll((Predicate<GenTableColumn>)(f => dictHtml.Contains(f.HtmlType))));
    if (Model.GenTable.SubTable != null && Model.GenTable.SubTableName.IsNotEmpty())
    {
        dicts.AddRange(Model.GenTable?.SubTable?.Columns?.FindAll((Predicate<GenTableColumn>)(f => dictHtml.Contains(f.HtmlType))));
    }
    List<GenTableColumn> cols = genTable.Columns;
    var customCtls = cols.Where(m => m.HtmlType == "customCtl").ToList();
}
<!--
* @@Descripttion: (@(genTable.FunctionName))
* @@version: (1.0)
* @@Author: (@(replaceDto.Author))
* @@Date: (@(replaceDto.AddTime))
* @@LastEditors: (@(replaceDto.Author))
* @@LastEditTime: (@(replaceDto.AddTime))
-->
<template>
    <div class="app-container">
        <el-form :model="queryParams" size="small" label-position="right" inline ref="queryForm" v-show="showSearch" 
        @@submit.native.prevent>
            @(replaceDto.VueQueryFormHtml)
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @@click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @@click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            @if(replaceDto.ShowBtnAdd)
            {
                <el-col :span="1.5">
                    <el-button type="primary" v-hasPermi="['@(replaceDto.PermissionPrefix):add']" plain icon="el-icon-plus" size="mini" @@click="handleAdd">新增</el-button>
                </el-col>
            }
            @if(replaceDto.ShowBtnEdit)
            {
                <el-col :span="1.5">
                    <el-button type="success" :disabled="single" v-hasPermi="['@(replaceDto.PermissionPrefix):edit']" plain icon="el-icon-edit" size="mini" @@click="handleUpdate">修改</el-button>
                </el-col>
            }
            @if(replaceDto.ShowBtnDelete)
            {
                <el-col :span="1.5">
                    <el-button type="danger" :disabled="multiple" v-hasPermi="['@(replaceDto.PermissionPrefix):delete']" plain icon="el-icon-delete" size="mini" @@click="handleDelete">删除</el-button>
                </el-col>
            }
            @if(replaceDto.ShowBtnExport)
            {
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download" size="mini" @@click="handleExport" v-hasPermi="['@(replaceDto.PermissionPrefix):export']">导出</el-button>
                </el-col>
            }
            <right-toolbar :showSearch.sync="showSearch" @@queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 数据区域 -->
        <el-table :data="dataList" v-loading="loading" ref="table" border highlight-current-row @@sort-change="sortChange" @@selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center"/>
            @(replaceDto.VueViewListHtml)
            <el-table-column label="操作" align="center" width="140">
                <template slot-scope="scope">
                    @if(replaceDto.ShowBtnEdit)
                    {
                        <el-button size="mini" v-hasPermi="['@(replaceDto.PermissionPrefix):edit']" type="success" icon="el-icon-edit" title="编辑" 
                        @@click="handleUpdate(scope.row)"></el-button>      
                    }
                    @if(replaceDto.ShowBtnDelete)
                    {
                        <el-button size="mini" v-hasPermi="['@(replaceDto.PermissionPrefix):delete']" type="danger" icon="el-icon-delete" title="删除" 
                        @@click="handleDelete(scope.row)"></el-button>
                    }
                </template>
            </el-table-column>
        </el-table>
        <pagination class="mt10" background :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @@pagination="getList" />

        <!-- 添加或修改@(genTable.FunctionName)对话框 -->
        <el-dialog :title="title" :lock-scroll="false" :visible.sync="open" >
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20" style="display: flex; flex-wrap: wrap;">
                    @(replaceDto.VueViewFormHtml)
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="text" @@click="cancel">取 消</el-button>
                <el-button type="primary" @@click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
    import { 
    list@(genTable.FunctionCode),
    add@(genTable.FunctionCode),
    del@(genTable.FunctionCode),
    update@(genTable.FunctionCode),
    get@(genTable.FunctionCode),
    @if(replaceDto.ShowBtnExport)
    {
        @:export@(genTable.FunctionCode),
    }
    @if(showCustomInput)
    {
        @:changeSort
    }
    } from '@@/api/@(CodeGeneratorTool.FirstLowerCase(genTable.ModuleCode))/@(CodeGeneratorTool.FirstLowerCase(genTable.FunctionCode)).js';
    @{
        bool isHasTreeCtl = false;
    }
    @foreach(var item in customCtls)
    {
        switch(item.CustomCtl)
        {
            case "deptTreeSelect":
                isHasTreeCtl = true;
                @:import { treeselect as @(item.CustomCtl) } from '@@/api/system/dept'
                @:import Treeselect from '@@riophae/vue-treeselect'
                @:import '@@riophae/vue-treeselect/dist/vue-treeselect.css'
                break;
        }

    }

    export default {
    name: "@(genTable.FunctionCode.ToLower())",
    components: { @(isHasTreeCtl?"Treeselect":"") },
    data() {
    return {
    labelWidth: "100px",
    formLabelWidth:"100px",
    // 选中@(replaceDto.FistLowerPk)数组
    ids: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    // 遮罩层
    loading: false,
    // 显示搜索条件
    showSearch: true,
    // 查询参数
    queryParams: {
    pageNum: 1,
    pageSize: 10,
    sort: undefined,
    sortType: undefined,
    @foreach(var item in genTable.Columns)
    {
        if(item.IsQuery == true)
        {
            @:@(item.CsharpFieldFl): undefined,
        }
    }
    },
    // 弹出层标题
    title: "",
    @foreach (var item in customCtls)
    {
        @:@(item.CustomCtl)Options:undefined,
    }
    // 操作类型 1、add 2、edit
    opertype: 0,
    // 是否显示弹出层
    open: false,
    // 表单参数
    form: {},
    columns: [
    @{
        index = 0;
    }
    @foreach(var column in genTable.Columns)
    {
        @:{ index: @index, key: '@(column.CsharpFieldFl)', label: `@(column.FieldDesc)`, checked:  @(index < 9?"true":"false")  },
        index = index + 1;
    }
    ],
    @foreach(var item in genTable.Columns)
    {
        if((item.HtmlType == "radio" || item.HtmlType == "select" || item.HtmlType == "checkbox"))
        {
            @:// @(item.FieldDesc)选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
            @:@(item.DictType != ""?item.DictType:$"{item.CsharpFieldFl}Options"): [],
        }
        else if(item.HtmlType == "datetime" && item.IsQuery == true)
        {
            @://@(item.FieldDesc)时间范围
            @:dateRange@(item.CsharpField): [],
        }
        else if(item.HtmlType == "customInput")
        {
            @:editIndex: -1,
        }
    }
    dataList: [],
    total: 0,
    rules: {
    @foreach(var column in genTable.Columns)
    {
        if(column.IsRequired==true && column.IsIncrement == false)
        {
            @:@(column.CsharpFieldFl): [
            @:{ required: true, message: "@(column.FieldDesc)不能为空", trigger: "@(column.HtmlType == "select"?"change":"blur")" }
            @:],
        }
    }
    },
    };
    },
    created() {    
    // 列表数据查询
    this.getList();
    @foreach(var item in customCtls)
    {
        @:this.@(item.CustomCtl)Query();
    }
    @{
        index = 0;
    }
    var dictParams = [
    @foreach (var item in dicts)
    {
        @if (item.DictType != "")
        {
            @:"@(item.DictType)",
        }
        index = index + 1;
    }
    ];
    @if(index > 0)
    {
        @:this.getDicts(dictParams).then((response) => {
        @:response.data.forEach((element) => {
        @:this[element.dictType] = element.list;
        @:});
        @:});
    }
    },
    methods: {
    // 查询数据
    getList() {
    @foreach(var item in genTable.Columns)
    {
        if(item.HtmlType == "datetime" && item.IsQuery == true)
        {
            @:this.addDateRange(this.queryParams, this.dateRange@(item.CsharpField), '@(item.CsharpField)');
        }
    }
    this.loading = true;
    list@(genTable.FunctionCode)(this.queryParams).then(res => {
    if (res.code == 200) {
    this.dataList = res.data.result;
    this.total = res.data.totalNum;
    this.loading = false;
    }
    })
    },
    @foreach(var item in customCtls)
    {
        @:@(item.CustomCtl)Query() {
            @:@(item.CustomCtl)().then((response) =>
            @:{
                @:this.@(item.CustomCtl)Options = response.data
            @:})
        @:},
    }
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 重置数据表单
    reset() {
      this.form = {
@foreach(var item in genTable.Columns)
{
    if(item.HtmlType == "checkbox")
    {
        @:@(item.CsharpFieldFl)Checked: [],
    }
    else
    {
        @:@item.CsharpFieldFl: undefined,
    }
}
      };
      this.resetForm("form");
    },
    // 重置查询操作
    resetQuery() {
      this.timeRange = [];
@foreach(var item in genTable.Columns)
{
    if(item.HtmlType == "datetime" && item.IsQuery == true)
    {
      @://@(item.FieldDesc)时间范围
      @:this.dateRange@(item.CsharpField)= [];
    }
}
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.@(replaceDto.FistLowerPk));
      this.single = selection.length != 1
      this.multiple = !selection.length;
    },
     // 自定义排序
    sortChange(column) {
      if (column.prop == null || column.order == null) {
        this.queryParams.sort = undefined;
        this.queryParams.sortType = undefined;
      } else {
        this.queryParams.sort = column.prop;
        this.queryParams.sortType = column.order;
      }

      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
      this.opertype = 1;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.@(replaceDto.FistLowerPk) || this.ids;

      this.$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
        .then(function () {
          return del@(genTable.FunctionCode)(Ids);
        })
        .then(() => {
          this.handleQuery();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.@(replaceDto.FistLowerPk) || this.ids;
      get@(genTable.FunctionCode)(id).then((res) => {
        const { code, data } = res;
        if (code == 200) {
          this.open = true;
          this.title = "修改数据";
          this.opertype = 2;

          this.form = {
            ...data,
@foreach(var item in genTable.Columns)
{
    if(item.HtmlType == "checkbox")
    {
                @:@(item.CsharpFieldFl)Checked: data.@(item.CsharpFieldFl) ? data.@(item.CsharpFieldFl).split(',') : [],
    }
}
          };
        }
      });
    },
@if(replaceDto.UploadFile == 1)
{
    @://图片上传成功方法
    @:handleUploadSuccess(column, filelist) {
      @:this.form[column] = filelist;
    @:},
}
@foreach(var item in genTable.Columns)
{
    if(item.HtmlType == "customInput")
    {
    @:// 显示编辑排序
    @:editCurrRow(rowId, str) {
      @:this.editIndex = rowId;
      @:let id = rowId + str;
      @:
      @:setTimeout(() => {
        @:document.getElementById(id).focus();
      @:}, 100);
    @:},
    @:// 保存排序
    @:handleChangeSort(info) {
      @:this.editIndex = -1;
      @:changeSort({ value: info.@(item.CsharpFieldFl), id: info.@(replaceDto.FistLowerPk) }).then(
        @:(response) => {
          @:this.msgSuccess("修改成功");
          @:this.getList();
        @:}
      @:);
    @:},
    }
}
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
@foreach(var item in genTable.Columns)
{
    if(item.HtmlType == "checkbox")
    {
          @:this.form.@(item.CsharpFieldFl) = this.form.@(item.CsharpFieldFl)Checked.toString();
    }
}
          if (this.form.@(replaceDto.FistLowerPk) != undefined && this.opertype === 2) {
            update@(genTable.FunctionCode)(this.form)
              .then((res) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
            })
          } else {
            add@(genTable.FunctionCode)(this.form)
              .then((res) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
            })
          }
        }
      });
    },
@if(replaceDto.ShowBtnExport)
{
    @:/** 导出按钮操作 */
    @:handleExport() {
      @:const queryParams = this.queryParams;
      @:this.$confirm("是否确认导出所有@(genTable.FunctionName)数据项?", "警告", {
        @:confirmButtonText: "确定",
        @:cancelButtonText: "取消",
        @:type: "warning",
      @:}).then(async () => {
          @:await export@(genTable.FunctionCode)(queryParams);
      @:})
    @:},
}
  },
};
</script>